// Charge l'ensemble des radars

function requestRadars() {
  var mapBounds = map.getBounds();
  var maxLng = mapBounds.getNorthEast().lng();
  var maxLat = mapBounds.getNorthEast().lat();
  var minLng = mapBounds.getSouthWest().lng();
  var minLat = mapBounds.getSouthWest().lat();
  
  var sqlQ = "SELECT TYPE, SPEED, LONG, LAT, SENS FROM 2596623 WHERE LONG <= '" + minLng + "' AND LONG >= '" + maxLng + "' AND LAT >= '" + minLat + "' AND LAT <= '" + maxLat +"'";
  var sql = encodeURIComponent(sqlQ);
  var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + sql);
  query.send(loadRadars);
}

function loadRadars(response) {
  // Load all radars
  var rows = response.getDataTable(); 
  for (var i=0; i<rows.getNumberOfRows(); i++) {
    var type = rows.getValue(i,0);
    if (type == "Rf") { // Radars fixes
      createRadarMarker('radars_fixes', rows, i);
    } else if (type == "Rm") { // Radars mobiles
      createRadarMarker('radars_mobiles', rows, i);       
    } else if (type == "Rfr") { // Radars feux rouges
      createRadarMarker('radars_feux', rows, i);
    }
  }
}

function createRadarMarker(layerName, rows, index) {
  var layer = layers[layerName];
  var type = rows.getValue(index,0);
  var speed = rows.getValue(index,1);
  var lng = rows.getValue(index,2);
  var lat = rows.getValue(index,3);
  var sens = rows.getValue(index,4);
  var point= new google.maps.LatLng(lat, lng); 
  
  var model = new Object();
  model['type'] = type;
  model['speed'] = speed;
  model['lat'] = lat;
  model['lng'] = lng;
  model['sens'] = sens;
  
  var myMarkerOpts = {
    position: point,
    title : layerName
  };
  
  if (layerName == 'radars_feux') {
    myMarkerOpts["icon"] = "./images/radars/" + type + ".bmp";
  } else  {
    myMarkerOpts["icon"] = "./images/radars/" + type + "-" + speed + ".bmp";
  }
  
  var marker = new google.maps.Marker(myMarkerOpts);
  var infoWindow = new google.maps.InfoWindow();
  
  infoWindow.setContent(layerName);
  google.maps.event.addListener(marker, 'click', function() {  
    if (openedInfoWindow != null) { 
      openedInfoWindow.close();
    }
    infoWindow.open(map, marker); 
    openedInfoWindow  = infoWindow;
  });              
  
  var markerDef = new Object();
  markerDef['id'] = type+speed+lat+lng+sens;
  markerDef['marker'] = marker;
  markerDef['infoWindow'] = infoWindow;
  markerDef['model'] = model;
  layer['markers'].push(markerDef);
  
}



